<template>
  <div class="app-container">
    <FilterSearch class="filter-search" :value="queryParams" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }"
      :config="configData" labelWidth="90px" position="right"></FilterSearch>
    <div class="main">
      <div class="table">
        <el-table stripe @selection-change="tableChange" :data="tableData.rows" border v-loading="tableData.loading"
          style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="id" width="60">
          </el-table-column>
          <el-table-column prop="dbName" label="数据库名称" width="120">
          </el-table-column>
          <el-table-column prop="dbSchema" label="schema" width="160">
          </el-table-column>
          <el-table-column prop="dbPort" label="数据库端口" width="90">
          </el-table-column>
          <el-table-column prop="dbUrl" label="数据库链接" width="500">
            <template v-slot="scope">
              <el-popover placement="top-start" :width="300" trigger="hover">
                <div style="max-height: 150px;">
                  <el-scrollbar :height="150">
                    {{ scope.row.dbUrl }}
                  </el-scrollbar>
                </div>
                <template #reference>
                  <div class="ellipsis_3">
                    {{ scope.row.dbUrl }}
                  </div>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="dbType" label="数据库类型" width="90">
            <template v-slot="scope">
              <div v-for="(item, index) in dbTypeList">
                <span v-if="item.value == scope.row.dbType">
                  {{ item.label }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="dbUsername" label="数据库账号" width="160">
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="160px">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.createdTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="修改时间" width="160px">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.updateTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="160">
            <template v-slot="scope">
              <el-button @click="handleClick(scope.row, 'update')" type="text" size="small">编辑</el-button>
              <el-button @click="handleClick(scope.row, 'copy')" type="text" size="small">复制</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination @current-change="currentChange" layout="total, prev, pager, next, jumper" :total="tableData.total"
          :current-page="queryParams.currentPage" :page-size="queryParams.size">
        </el-pagination>
      </div>
    </div>
    <el-dialog v-model="rowData.diaVis" :title="rowData.title" :close-on-click-modal="false" :show-close="false"
      width="900px">
      <div class="box-container">
        <el-form label-position="left" label-width="120px" :model="rowData.formInline" :rules="rules" ref="formState">
          <el-row>
            <el-col :span="24">
              <el-form-item label="数据库名称:" prop="dbName">
                <el-input v-model="rowData.formInline.dbName" placeholder="请输入数据库名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="schema:" prop="dbSchema">
                <el-input v-model="rowData.formInline.dbSchema" placeholder="请输入schema" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="数据库端口:" prop="dbPort">
                <el-input maxlength="4"
                  @input="rowData.formInline.dbPort = rowData.formInline.dbPort.replace(/[^0-9.]/g, '')"
                  v-model="rowData.formInline.dbPort" placeholder="请输入数据库名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="数据库链接:" prop="dbUrl">
                <el-input v-model="rowData.formInline.dbUrl" placeholder="请输入数据库链接" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="数据库类型:" prop="dbType">
                <el-select v-model="rowData.formInline.dbType" placeholder="请选择数据库">
                  <el-option v-for="(item, ind) in dbTypeList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="数据库账号:" prop="dbUsername">
                <el-input v-model="rowData.formInline.dbUsername" placeholder="请输入数据库账号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="数据库密码:" prop="dbPassword">
                <el-input v-model="rowData.formInline.dbPassword" type="password" placeholder="请输入数据库密码" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit">
            测试连接
          </el-button>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit" :disabled="rowData.submitStatus">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { ref, reactive, computed, onBeforeMount, onBeforeUnmount } from "vue"
import { formatDate } from "@/utils/index.js"
import { getList, selectOne, insertDatabase, updateDatabase, delateDatabase, testDataBase } from "@/api/dataBase.js";
import { formData } from "@/utils/validate.js"
export default {
  setup() {
    const { proxy } = getCurrentInstance();

    const tableData = reactive({
      rows: [],
      total: 0,
      loading: false,
      selection: []
    });

    const queryParams = ref({
      currentPage: 1,
      size: 10
    });
    const timeOut = {
      setTime1: null
    }
    const rowData = reactive({
      diaVis: false,
      formInline: {},
      title: "新增数据库配置",
      formStatus: 0,
      submitStatus: true
    })

    const dbTypeList = ref([
      {
        label: "达梦",
        value: 1
      },
      {
        label: "mysql",
        value: 2
      },
      {
        label: "sql server",
        value: 3
      },
      {
        label: "oracle",
        value: 4
      }
    ]);

    const configData = computed(() => {
      let config = {
        itemConfig: [
        ],
        operate: [
          {
            icon: "RefreshLeft",
            type: "primary",
            name: "重置",
            handleClick: reset,
            rule: true,
          },
          {
            icon: "Plus",
            type: "primary",
            name: "新增",
            handleClick: insert,
            rule: true,
          },
          {
            icon: "Delete",
            type: "primary",
            name: "批量删除",
            handleClick: allDel,
            rule: true,
          }
        ],
        rules: {},
      };
      return config;
    })
    const rules = computed(() => {
      let rules = {
        dbName: [
          { required: true, trigger: "blur", message: "请输入数据库名称" },
          { required: true, trigger: "change", message: "请输入数据库名称" },
        ],
        dbSchema: [
          { required: true, trigger: "blur", message: "请输入schema" },
          { required: true, trigger: "change", message: "请输入schema" },
        ],
        dbPort: [
          { required: true, trigger: "blur", message: "请输入数据库端口" },
          { required: true, trigger: "change", message: "请输入数据库端口" },
        ],
        dbUrl: [
          { required: true, trigger: "blur", message: "请输入数据库链接" },
          { required: true, trigger: "change", message: "请输入数据库链接" },
        ],
        dbType: [
          { required: true, trigger: "blur", message: "请选择数据库类型" },
          { required: true, trigger: "change", message: "请选择数据库类型" },
        ],
        dbUsername: [
          { required: true, trigger: "blur", message: "请输入数据库账号" },
          { required: true, trigger: "change", message: "请输入数据库账号" },
        ],
        dbPassword: [
          { required: true, trigger: "blur", message: "请输入数据库密码" },
          { required: true, trigger: "change", message: "请输入数据库密码" },
        ]
      }
      return rules;
    })
    const getDate = (date) => {
      return formatDate(date)
    }
    const currentChange = (currentPage) => {
      proxy.queryParams.currentPage = currentPage;
      getLoad();
    }
    const tableChange = (selection) => {
      proxy.tableData.selection = selection;
    }
    const getLoad = () => {
      proxy.tableData.loading = true;
      getList(proxy.queryParams).then(res => {
        proxy.tableData.loading = false;
        if (res.status == 'success') {
          ElMessage.success('查询成功');
        } else {
          ElMessage.error('查询失败');
          return;
        }
        proxy.tableData.rows = res.data.records;
        proxy.tableData.total = res.data.total;
      })
    }
    const reset = () => {
      proxy.queryParams = {
        currentPage: 1,
        size: 10
      }
      getLoad();
    }
    const insert = () => {
      proxy.rowData.title = '新增数据库配置';
      proxy.rowData.diaVis = true;
      proxy.rowData.formStatus = 0;
      proxy.rowData.formInline = {};
    }
    const handleClick = (row, type) => {
      switch (type) {
        case 'update':
          selectOne(row).then(res => {
            proxy.rowData.formInline = res.data;
            proxy.rowData.title = '编辑数据库配置';
            proxy.rowData.diaVis = true;
            proxy.rowData.formStatus = 1;
            console.log(JSON.stringify(res.data));
          })
          break;
        case 'copy':
          selectOne(row).then(res => {
            proxy.rowData.formInline = res.data;
            proxy.rowData.formInline.id = null;

            proxy.rowData.title = '复制数据库配置';
            proxy.rowData.diaVis = true;
            proxy.rowData.formStatus = 0;
            console.log(JSON.stringify(res.data));
          })
          break;
        case 'diaVis2':
          break;
        default:
          break;
      }
    }
    const submit = () => {
      switch (proxy.rowData.formStatus) {
        case 0:
          proxy.$refs.formState.validate(valid => {
            if (valid) {
              if (proxy.rowData.submitStatus) {
                testDataBase(proxy.rowData.formInline).then(res => {
                  if (res.data) {
                    proxy.rowData.submitStatus = false;
                    ElMessage.success("测试连接成功");
                  } else {
                    ElMessage.error("测试连接失败");
                  }
                  return;
                })
              } else {
                insertDatabase(proxy.rowData.formInline).then(res => {
                  if (res.status == 'success') {
                    ElMessage.success(res.msg);
                    cancel();
                    getLoad();
                  } else {
                    ElMessage.error(res.msg);
                    return;
                  }
                })
              }
            }
          })
          break;
        case 1:
          proxy.$refs.formState.validate(valid => {
            if (valid) {
              if (proxy.rowData.submitStatus) {
                testDataBase(proxy.rowData.formInline).then(res => {
                  if (res.data) {
                    proxy.rowData.submitStatus = false;
                    ElMessage.success("测试连接成功");
                  } else {
                    ElMessage.error("测试连接失败");
                  }
                  return;
                })
              } else {
                updateDatabase(proxy.rowData.formInline).then(res => {
                  if (res.status == 'success') {
                    ElMessage.success(res.msg);
                    cancel();
                    getLoad();
                  } else {
                    ElMessage.error(res.data);
                    return;
                  }
                })
              }
            }
          })
          break;
        default:
          break;
      }
    }
    const cancel = () => {
      proxy.rowData.formInline = {};
      timeOut.setTime1 = setTimeout(() => {
        proxy.$refs.formState.clearValidate();
        proxy.rowData.diaVis = false;
        proxy.rowData.status = 0;
      }, 50);
    }
    const allDel = () => {
      if (proxy.tableData.selection.length <= 0) {
        ElMessage.info('请选择数据');
        return;
      }
      let ids = proxy.tableData.selection.map(it => {
        return it.id;
      })
      delateDatabase(formData({ ids })).then(res => {
        if (res.status == 'success') {
          ElMessage.success(res.msg);
          getLoad();
        } else {
          ElMessage.error('删除失败');
          return;
        }
      })
    }

    onBeforeMount(() => {
      getLoad();
    })

    onBeforeUnmount(() => {
      for (const key in timeOut) {
        if (timeOut[key]) {
          clearTimeout(timeOut[key]);
        }
      }
    })
    return {
      queryParams, configData, rowData, tableData, rules, dbTypeList, currentChange, tableChange, submit, getDate,
      handleClick, cancel
    }
  }
}


</script>
<style lang="scss" scoped>
$border-color: #c1c5cd;

.main {
  .page {
    padding: 10px 0;
    float: right;
  }


}

.el-select {
  width: 100%;
}

.ellipsis_3 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>